package server;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {
    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        // 加载解析相关的配置
        loadServer();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        ServerSocket serverSocket = new ServerSocket(mapper.getPort());
        System.out.println("=====>>>Minicat start on port：" + mapper.getPort());

        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, mapper);
            threadPoolExecutor.execute(requestProcessor);
        }
    }


    private Mapper mapper = new Mapper();

    /**
     * 加载server，作业按照只有一个server处理
     */
    private void loadServer() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            Element service = (Element) rootElement.selectSingleNode("Service");

            Element connector = (Element) service.selectSingleNode("Connector");
            String port = connector.attributeValue("port");
            //设置端口
            mapper.setPort(Integer.valueOf(port));

            Element engine = (Element) service.selectSingleNode("Engine");
            List<Element> hosts = engine.selectNodes("Host");
            for (int i = 0; i < hosts.size(); i++) {
                //host节点
                Element host = hosts.get(i);
                //解析并加载host
                loadHost(host);
            }
            System.out.println("加载完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadHost(Element host) {
        Mapper.MappedHost mappedHost = mapper.new MappedHost();

        String name = host.attributeValue("name");
        String appBase = host.attributeValue("appBase");

        mappedHost.setName(name);
        mappedHost.setAppBase(appBase);

        File appBaseFile = new File(appBase);
        if (appBaseFile.isDirectory()) {
            //appBase路径为文件夹
            File[] apps = appBaseFile.listFiles();
            for (int i = 0; i < apps.length; i++) {
                //webapp下的一个项目
                File app = apps[i];
                if (app.isDirectory()) {
                    //部署的项目为文件夹
                    File[] files = app.listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File pathname) {
                            return pathname.getName().equals("web.xml");
                        }
                    });
                    if (files.length == 1) {
                        //解析web.xml  加载servlet
                        loadServlet(mappedHost, appBase, app.getName(), files[0]);
                        mapper.getHostMap().put(name, mappedHost);
                    }
                }
            }
        }
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(Mapper.MappedHost mappedHost, String appBase, String contextName, File file) {
        Mapper.MappedContext mappedContext = mapper.new MappedContext();
        mappedContext.setName(contextName);
        mappedHost.getContextMap().put(contextName, mappedContext);
        try {
            InputStream resourceAsStream = new FileInputStream(file);
            SAXReader saxReader = new SAXReader();

            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                FileClassLoader fileClassLoader = new FileClassLoader(appBase + "/" + contextName + "/");
                Class aClass = fileClassLoader.myLoadClass(servletClass);
                HttpServlet o = (HttpServlet) aClass.newInstance();

                mappedContext.getServletMap().put(urlPattern, o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
